<template>
  <div class="abnormal">
    <c-list :column="3">
      <c-list-item label="整改任务号" :value="detail.taskCode" />
      <c-list-item label="所属验收任务号" :value="detail.acceptTaskCode" />
      <c-list-item label="门店建设项目号" :value="detail.constCode" />
      <c-list-item label="所属门店编码" :value="detail.shopCode" />
      <c-list-item label="所属门店" :value="detail.shopName" />
      <c-list-item label="所属办事处" :value="detail.officeName" />
      <c-list-item label="报图类型" dict-type-code="MARKET_TYPE" :value="detail.marketType" />
      <c-list-item label="门店建设类型" dict-type-code="CONST_TYPE" :value="detail.constType" />
      <c-list-item label="整改类型" dict-type-code="ACCEPT_TYPE" :value="detail.rectifyType" />
      <c-list-item label="整改步骤" dict-type-code="RECTIFY_STEPS" :value="detail.steps" />
      <c-list-item v-if="rectifyType === 'SOFT'" label="责任归属" :value="detail.belongDuty" />
    </c-list>
    <c-section title="整改异常清单">
      <template v-if="rectifyType==='HARD'">
        <c-table-box checkbox hide-func :table-height="200" :data="tableData" :table-row-key="tableRowKey" :table-config="tableConfig" @selection-change="selectionChangeHandle">
          <template #btn>
            <c-button type="primary" @click="addTableRow">新增</c-button>
            <c-button type="primary" @click="removeTableRow">删除</c-button>
            <el-upload
              style="margin:0 10px"
              :action="action"
              :headers="headers"
              :multiple="false"
              name="file"
              :show-file-list="false"
              accept=".xlsx"
              :on-success="importHandle"
            >
              <c-button type="primary">导入</c-button>
            </el-upload>
            <c-button type="primary" @click="downTemplate">下载导入模板</c-button>
          </template>
        </c-table-box>
      </template>
      <template v-else>
        <c-table-box checkbox hide-func table-height="400px" :data="softTableData" :table-row-key="tableRowKey" :table-config="softTableConfig" @selection-change="selectionChangeHandle">
          <template #btn>
            <c-button type="primary" @click="addTableRow">新增</c-button>
            <c-button type="primary" @click="removeTableRow">删除</c-button>
            <el-upload
              style="margin:0 10px"
              :action="action"
              :headers="headers"
              :multiple="false"
              name="file"
              :show-file-list="false"
              accept=".xlsx"
              :on-success="importHandle"
            >
              <c-button type="primary">导入</c-button>
            </el-upload>
            <c-button type="primary" @click="downTemplate">下载导入模板</c-button>
          </template>
        </c-table-box>
      </template>
    </c-section>
    <c-section title="附件上传">
      <c-file-table-box v-model="files" type-code="ACCESS144" :table-height="200" belong-model="ACCEPT_RECTIFY_TASK" :model-id="$route.query.id" />
    </c-section>
    <div class="btn-container">
      <c-button @click="cancelHandle">取消</c-button>
      <c-button type="primary" @click="confirmHandle">提交</c-button>
    </div>
  </div>
</template>
<script>
import { postShopException } from '@/api/decorate'
import { getOneDetail, importTemplate } from '@/api/rectify'
import { fileDown } from '@/utils'
import { getToken } from '@/utils/auth'
export default {
  name: 'RectifyAbnormal',
  props: {
    rectifyType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      activeTab: '',
      detail: {},
      files: [], // 异常附件
      tableConfig: {
        interfacePath: '',
        setting: [
          {
            prop: 'decorationRange',
            label: '装修范围',
            render: (h, row) => {
              return h('c-dict-select', {
                props: {
                  dictTypeCode: 'DECORATION_RANGE',
                  value: row.decorationRange
                },
                on: {
                  input: v => {
                    this.$set(row, 'decorationRange', v)
                  }
                }
              })
            }
          },
          {
            prop: 'belongDuty',
            label: '责任归属',
            render: (h, row) => {
              return h('c-dict-select', {
                props: {
                  dictTypeCode: 'BELONG_DUTY',
                  value: row.belongDuty
                },
                on: {
                  input: v => {
                    this.$set(row, 'belongDuty', v)
                  }
                }
              })
              // return h('c-remote-select', {
              //   props: {
              //     url: '/api/v1/configAcceptDuty/page',
              //     method: 'POST',
              //     value: row.belongDuty,
              //     valueName: 'belongDuty',
              //     labelName: 'belongDuty',
              //     filtersRaw: [
              //       { key: 'acceptType', value: this.rectifyType, operator: '=' },
              //       { key: 'enable', value: '1', operator: '=' }
              //     ]
              //   },
              //   attrs: {
              //     placeholder: '请选择责任归属'
              //   },
              //   on: {
              //     input: v => {
              //       this.$set(row, 'belongDuty', v)
              //     }
              //   }
              // })
            }
          },
          {
            prop: 'problemCategory',
            label: '问题类型',
            render: (h, row) => {
              return h('c-remote-select', {
                props: {
                  url: '/api/v1/configAcceptProblem/page',
                  method: 'POST',
                  value: row.problemCategory,
                  valueName: 'problemClass',
                  labelName: 'problemClass',
                  filtersRaw: [
                    { key: 'acceptType', value: 'HARD', operator: '=' },
                    { key: 'enable', value: '1', operator: '=' }
                  ]
                },
                attrs: {
                  placeholder: '请选择问题类型'
                },
                on: {
                  input: v => {
                    this.$set(row, 'problemCategory', v)
                  }
                }
              })
            }
          },
          {
            prop: 'exceptionDesc',
            label: '整改异常问题描述',
            edit: {
              canEdit: true,
              editType: 'text',
              maxlength: 2000
            }
          },
          // {
          //   prop: 'isRelateDeduction',
          //   label: '是否涉及扣款',
          //   render: (h, row) => {
          //     return h('c-dict-select', {
          //       props: {
          //         dictTypeCode: 'BOOLEANS',
          //         value: row.isRelateDeduction
          //       },
          //       on: {
          //         input: v => {
          //           this.$set(row, 'isRelateDeduction', v)
          //         }
          //       }
          //     })
          //   }
          // },
          // {
          //   prop: 'deductionDesc',
          //   label: '扣款说明',
          //   edit: {
          //     canEdit: true,
          //     editType: 'text'
          //   }
          // },
          {
            prop: 'remark',
            label: '备注',
            edit: {
              canEdit: true,
              editType: 'text',
              maxlength: 2000
            }
          }
        ]
      },
      softTableConfig: {
        interfacePath: '',
        setting: [
          {
            prop: 'problemCategory',
            label: '问题类型',
            render: (h, row) => {
              return h('c-remote-select', {
                props: {
                  url: '/api/v1/configAcceptProblem/page',
                  method: 'POST',
                  value: row.problemCategory,
                  valueName: 'problemClass',
                  labelName: 'problemClass',
                  filtersRaw: this.softFiltersRaw
                },
                attrs: {
                  placeholder: '请选择问题类型'
                },
                on: {
                  input: v => {
                    this.$set(row, 'problemCategory', v)
                    this.$set(row, 'stockoutType', '')
                  }
                }
              })
            }
          },
          {
            prop: 'stockoutType',
            label: '缺货类别',
            render: (h, row) => {
              return h('c-dict-select', {
                props: {
                  disabled: row.problemCategory !== '产品缺货',
                  dictTypeCode: 'STOCKOUT_TYPE',
                  value: row.stockoutType
                },
                on: {
                  input: v => {
                    this.$set(row, 'stockoutType', v)
                  }
                }
              })
            }
          },
          {
            prop: 'exceptionDesc',
            label: '整改异常问题描述',
            edit: {
              canEdit: true,
              editType: 'text',
              maxlength: 2000
            }
          },
          {
            prop: 'solution',
            label: '建议解决方案',
            edit: {
              canEdit: true,
              editType: 'text',
              maxlength: 2000
            }
          },
          {
            prop: 'remark',
            label: '备注',
            edit: {
              canEdit: true,
              editType: 'text',
              maxlength: 2000
            }
          }
        ]
      },
      tableData: [],
      selections: [],
      // 软装数据
      softTableData: [],
      softSelections: [],
      headers: {
        'X-Token': this.$store.getters.token ? getToken() : '',
        'Authorization': this.$store.getters.token ? 'Bearer ' + getToken() : ''
      }
    }
  },
  computed: {
    action() {
      if (this.rectifyType === 'HARD') {
        return '/slm-admin/api/v1/acceptRectifyTask/hardImportExcel'
      } else {
        return '/slm-admin/api/v1/acceptRectifyTask/softImportExcel'
      }
    },
    // rectifyType === 'SOFT'" label="责任归属" :value="detail.belongDuty
    softFiltersRaw() {
      const b = this.detail.belongDuty
      const t = [
        { key: 'acceptType', value: 'SOFT', operator: '=' },
        { key: 'enable', value: '1', operator: '=' }
      ]
      if (b) {
        t.push({ key: 'belongDuty', value: b, operator: '=' })
      }
      if (this.problemTypes.length > 0) {
        t.push({ key: 'problemClass', value: `[${this.problemTypes.join(',')}]`, operator: 'in' })
      }
      return t
    },
    problemTypes() {
      const problemList = this.detail.problemList || []
      const t = []
      problemList.forEach(e => {
        const pl = e.problemDetailDTOList || []
        pl.forEach(p => {
          t.push(p.problemType)
        })
      })
      return t
    }
  },
  created() {
    this.getDetail()
  },
  methods: {
    selectionChangeHandle(v) {
      if (this.rectifyType === 'SOFT') {
        this.softSelections = v
      } else {
        this.selections = v
      }
    },
    tableRowKey(row) {
      return row._key
    },
    addTableRow() {
      if (this.rectifyType === 'SOFT') {
        this.softTableData.unshift({
          problemCategory: '',
          stockoutType: '',
          exceptionDesc: '',
          solution: '',
          remark: '',
          belongDuty: this.detail.belongDuty,
          _key: Math.floor(Math.random() * 0xfffff).toString(16)
        })
      } else {
        this.tableData.unshift({
          decorationRange: '',
          belongDuty: '',
          problemCategory: '',
          exceptionDesc: '',
          // isRelateDeduction: '',
          // deductionDesc: '',
          remark: '',
          _key: Math.floor(Math.random() * 0xfffff).toString(16)
        })
      }
    },
    removeTableRow() {
      let d = this.tableData; let s = this.selections
      if (this.rectifyType === 'SOFT') {
        d = this.softTableData
        s = this.softSelections
      }
      if (!this.singleJudge(s, '删除', false)) {
        this.$message.warning('请选择数据！')
        return
      }
      const result = d.filter(e => {
        return !s.includes(e)
      })
      if (this.rectifyType === 'SOFT') {
        this.softTableData = result
        this.softSelections = []
      } else {
        this.tableData = result
        this.selections = []
      }
    },
    getDetail() {
      const { id } = this.$route.query
      getOneDetail(id).then(res => {
        this.detail = res.data
      })
    },
    cancelHandle() {
      this.$store.dispatch('views/goFirst')
    },
    validate() {
      // 2.当整改类型为“硬装”时，装修范围、责任归属、是否设计扣款必填；
      // 3.当整改类型为软装时，整改异常问题描述、建议解决方案必填；
      if (this.rectifyType === 'HARD') {
        if (this.tableData.length === 0) {
          this.$message.warning('请填写整改异常清单！')
          return Promise.reject()
        }
        for (const item of this.tableData) {
          const { decorationRange, belongDuty } = item
          if (!decorationRange || !belongDuty) {
            this.$message.warning('装修范围、责任归属必填！')
            return Promise.reject()
          }
        }
      }
      if (this.rectifyType === 'SOFT') {
        if (this.softTableData.length === 0) {
          this.$message.warning('请填写整改异常清单！')
          return Promise.reject()
        }
        for (const item of this.softTableData) {
          const { exceptionDesc, solution, stockoutType, problemCategory } = item
          if (!exceptionDesc || !solution || (problemCategory === '产品缺货' && !stockoutType)) {
            this.$message.warning('产品缺货时缺货类别、整改异常问题描述、建议解决方案必填！')
            return Promise.reject()
          }
        }
      }
      return Promise.resolve()
    },
    confirmHandle() {
      // console.log('附件上传', this.files)
      // return
      return this.validate().then(() => {
        let typeCode = 'EXCEPT027'
        // eslint-disable-next-line no-unused-vars
        let name = 'RectifyHard'
        if (this.rectifyType === 'SOFT') {
          typeCode = 'EXCEPT028'
          name = 'RectifySoft'
        }
        const fileList = this.files.map(el => { return el.response.data })
        return this.$gsec(typeCode).then(([cfg, ecd]) => {
          const d = this.detail
          ecd.constCode = d.constCode
          ecd.bizCode = d.taskCode
          ecd.modelId = d.id
          ecd.shopExceptionDetailDTOS = [...this.tableData, ...this.softTableData]
          this.$set(ecd, 'shopAttachmentDTOS', fileList)
          console.log(ecd)
          // return
          return postShopException(ecd).then(res => {
            this.$message.success('操作成功！')
            // this.$router.push({ name })
            this.$store.dispatch('views/goBack')
          })
        })
      })
    },
    // 导入
    importHandle(response, file, fileList) {
      // console.log(response, file, fileList)
      if (response.success !== 1) {
        this.$message.error(response.msg)
        return
      }
      if (this.rectifyType === 'SOFT') {
        this.softTableData.unshift(...response.data)
      } else {
        this.tableData.unshift(...response.data)
      }
    },
    // 下载模板
    downTemplate() {
      return importTemplate(this.rectifyType === 'SOFT' ? 'soft' : 'hard').then(res => {
        const t = URL.createObjectURL(res)
        fileDown(t, '整改异常导入模板.xlsx')
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.abnormal{
  padding-top: 12px;
}
</style>
